<?php
namespace app\platform\controller\admin;
use app\BaseController;
use app\common\logic\DataLogic;
use app\common\model\account\AccountModel;
use app\common\model\account\ShopAccountModel;
use app\common\model\AppModel;
use app\common\model\CustomerServiceModel;
use app\common\model\OrderModel;
use app\common\model\ShopModel;
use app\common\model\ShopPaymentModel;
use app\common\model\MiniappFreeModel;
use app\common\helper\open\OpenPlatformHelper;
use think\facade\Db;

class Shop extends BaseController{
    
    
     public function getPassagewayList()
    {
        $where = [];
        
        $keyword = $this->request->param('keyword');
        if(!empty($keyword)){
            $where[] = ['name|code|legal_persona_wechat|legal_persona_name','LIKE','%'.$keyword.'%'];
        }
        $count = MiniappFreeModel::where($where)->count();
        $datas = MiniappFreeModel::where($where)
            ->order(['free_id'=>'desc'])
            ->limit($this->request->limit)->page($this->request->page)
            ->select()
            ->append(['add_time_format','code_type_means','status_means'])
            ->toArray();
        return $this->success([
            'total' => $count,
            'list'  => $datas
        ]);
    } 
 public function savePassageway()
    {
        $name = $this->request->param('name');
        $code = $this->request->param('code');
        $code_type = $this->request->param('code_type/d');
        $legal_persona_wechat = $this->request->param('legal_persona_wechat');
        $legal_persona_name  = $this->request->param('legal_persona_name');
        if(empty($name)){
            return $this->error('企业名称不能为空');
        }
        if(empty($code)){
            return $this->error('企业证件号码不能为空');
        }
        if(!in_array($code_type, [1,2,3])){
            return $this->error('证件类型不正确');
        }
        if(empty($legal_persona_wechat)){
            return $this->error('法人绑定银行卡的微信不能为空');
        }
        if(empty($legal_persona_name)){
            return $this->error('法人真实姓名不能为空');
        }

        if(null !== MiniappFreeModel::where([['status','in',[0,1]],['code','=',$code],['code_type','=',$code_type]])->find()){
            return $this->error('该证件正在审核或者审核通过了');
        }
       $OpenPlatformHelper = new OpenPlatformHelper();
       $res  = $OpenPlatformHelper->applyFree([
            'name' => $name,
            'code' => $code,
            'code_type' => $code_type,
            'legal_persona_wechat' => $legal_persona_wechat,
            'legal_persona_name' => $legal_persona_name,
            'component_phone' => '18096404936'
       ]);
        if($res['errcode'] == 0){
            $MiniappFreeModel = new MiniappFreeModel();
            $MiniappFreeModel->name = $name;
            $MiniappFreeModel->code = $code;
            $MiniappFreeModel->code_type = $code_type;
            $MiniappFreeModel->legal_persona_wechat = $legal_persona_wechat;
            $MiniappFreeModel->legal_persona_name = $legal_persona_name;
            $MiniappFreeModel->status = 0;
            $MiniappFreeModel->save();
            return $this->success();
        }else{
            return $this->error($res['errmsg'].$res['errcode']);
        }
    }
    public function index()
    {
        $name = $this->request->param('name');
        $mobile=$this->request->param('mobile');
        $app_id=$this->request->param('app_id/d');
        $status = $this->request->param('status/d',1);

        if($status==1)
            $where=[ ['type','=',2], ['expire_time','>=',$this->request->time()]];
        if($status==2)
            $where=[ ['type','=',2], ['expire_time','between',[$this->request->time(),$this->request->time()+30*86400]]];
        if($status==3)
            $where=[ ['type','=',1], ['expire_time','>=',$this->request->time()]];
        if($status==4)
            $where=[['expire_time','<',$this->request->time()]];

        //搜索条件判断
        if(!empty($name)){
            $where[]=['name','=',$name];
        }
        if(!empty($mobile)){
            if(null !== $account=AccountModel::where([['is_delete','=',0],['mobile','=',$mobile],])->find()){
                $shop_ids=ShopAccountModel::where([
                    ['account_id','=',$account->account_id],
                    ['role_id','=',1]
                ])->column('shop_id') ?? [];
                $where[]=['shop_id','in',$shop_ids];
            }else{
                $where[]=['shop_id','in',[]];
            }
        }

        if(!empty($app_id)) $where[]=['app_id','=',$app_id];

        $shop = new ShopModel();
        $shop=$shop->with(['relation'=>function($query){
            $query->with(['account'])->where([['role_id','=',1]])->append(['shop_token']);
        },'app','kefu']);

        if($status==1 || $status==3)
            $order=['add_time'=>'desc'];
        if($status==2)
            $order=['expire_time'=>'asc'];
        if($status==4)
            $order=['expire_time'=>'desc'];

        $append=['add_time_format','expire_time_format','status_mean'];
        $return=DataLogic::getDataList($shop,$where,$order,'*',$this->request->limit,$this->request->page,$append);

        $app_list=AppModel::where([
            ['is_delete','=',0]
        ])->order(['sort'=>'desc','is_tui'=>'desc','add_time'=>'desc'])
            ->select()->toArray();

        $return['app_list']=$app_list;
        return $this->success($return);

    }

    public function show()
    {
        $shop_id=$this->request->param('shop_id/d',0);
        if(null === $shop = ShopModel::find($shop_id)){
            return $this->error('商铺不存在');
        }
        $shop->app->append(['type_name']);
        $detail=[
            'name'=>$shop->name,
            'app_name'=>$shop->app->name,
        ];
        return $this->success(['detail'=>$detail]);
    }
    
    public function showShopStore()
    {
        $shop_id=$this->request->param('shop_id/d',0);
        if(null === $shop = ShopModel::find($shop_id)){
            return $this->error('商铺不存在');
        }
        $detail=[
            'number'=>$shop->number,
        ];
        return $this->success(['detail'=>$detail]);
    }
    
    public function saveShopStore()
    {
        $shop_id = $this->request->param('shop_id/d',0);
        $number  = $this->request->param('number/d',0);
        if(null === $shop = ShopModel::find($shop_id)){
            return $this->error('商铺不存在');
        }
        if($number == 0) {
            return $this->error('请设置商户门店数量');
        }
        // 获取当前商铺已经设置的门店数量
        $shop->number = $number;
        $shop->save();
        return $this->success();
    }
    
    

    public function renew()
    {
        $shop_id=$this->request->param('shop_id/d',0);
        $days=$this->request->param('days/d');
        $price=$this->request->param('price/f');
        if(empty($days) || $days<=0){
            return $this->error('请输入续费天数且天数不能小于0');
        }
        if(empty($price) || $price<=0){
            return $this->error('请输入续费金额且金额不能小于0');
        }
        if(null === $shop = ShopModel::find($shop_id)){
            return $this->error('商铺不存在');
        }
        $expire_time=($shop->expire_time < $this->request->time() ? $this->request->time() : $shop->expire_time) + $days * 86400;
        $shop->expire_time=$expire_time;
        $shop->type=2;
        $shop->save();

        cache('miniapp_'.$shop_id,null); //删除小程序的缓存

        //添加一条记录 后期补充
        $order = new OrderModel();
        $order->shop_id=$shop_id;
        $order->type=3;
        $order->app_name=$shop->app->iden;
        $order->num=$days;
        $order->price=$price;
        $order->is_paid=1;
        $order->save();

        return $this->success('续费成功');

    }

    public function shopdisplay()
    {
        $shop_id=$this->request->param('shop_id/d',0);
        if(null === $shop = ShopModel::find($shop_id)){
            return $this->error('商铺不存在');
        }
        $shop->app->append(['type_name']);
        $detail=[
            'is_tui'=>$shop->is_display,
        ];
        return $this->success(['detail'=>$detail]);
    }

    public function shopdisplayis()
    {
        $shop_id = $this->request->param('shop_id/d',0);
        $is_tui  = $this->request->param('is_tui/d');
        if(null === $shop = ShopModel::find($shop_id)){
            return $this->error('商铺不存在');
        }
        $shop->is_display=$is_tui;
        $shop->save();

        return $this->success('续费成功');

    }

    public function getKefuList()
    {
        $name = $this->request->param('name');
        $mobile=$this->request->param('mobile');
        $customer_service_id = $this->request->param('customer_service_id/d');
        $where=[
            ['is_delete','=',0]
        ];


        //搜索条件判断
        if(!empty($name)) $where[]=['name','=',$name];
        if(!empty($mobile)) $where[]=['mobile','=',$mobile];
        if(!empty($customer_service_id)) $where[]=['customer_service_id','<>',$customer_service_id];

        $customer_service = new CustomerServiceModel();
        $order=['add_time'=>'desc'];
        $append=['add_time_format'];
        $return=DataLogic::getDataList($customer_service,$where,$order,'*',$this->request->limit,$this->request->page,$append);

        return $this->success($return);
    }

    public function showKefu()
    {
        $customer_service_id=$this->request->param('customer_service_id/d',0);
        if($customer_service_id==0){
            return $this->success([]);
        }
        if(null === $customer_service = CustomerServiceModel::find($customer_service_id)){
            return $this->error('客服不存在');
        }
        if($customer_service->is_delete != 0){
            return $this->error('客服不存在');
        }
        $detail=[
            'name'=>$customer_service->name,
            'qrcode'=>$customer_service->qrcode,
            'mobile'=>$customer_service->mobile,
        ];
        return $this->success(['detail'=>$detail]);
    }

    public function saveKefu()
    {
        $customer_service_id=$this->request->param('customer_service_id/d',0);
        $name = $this->request->param('name');
        $qrcode=$this->request->param('qrcode');
        $mobile = $this->request->param('mobile');

        if(empty($name) || mb_strlen($name)>20) return $this->error('请填写客服名称且长度不能多余20');
        if(empty($qrcode)) return $this->error('请上传二维码');
        if(empty($mobile) || !is_mobile($mobile)) return $this->error('请输入正确的手机号');

        if($customer_service_id != 0){
            if(null === $customer_service = CustomerServiceModel::find($customer_service_id)){
                return $this->error('客服不存在');
            }
            if($customer_service->is_delete != 0){
                return $this->error('客服不存在');
            }
            $pre_qrcode=$customer_service->qrcode;
        }else{
            $customer_service = new CustomerServiceModel();
            $pre_qrcode=null;
        }
        $customer_service->name=$name;
        $customer_service->qrcode=$qrcode;
        $customer_service->mobile=$mobile;
        $customer_service->save();

        imgReplaceAct($qrcode,$pre_qrcode);
        return $this->success('保存成功');
    }

    public function delKefu()
    {
        $customer_service_id=$this->request->param('customer_service_id/d',0);
        if(null === $customer_service = CustomerServiceModel::find($customer_service_id)){
            return $this->error('客服不存在');
        }
        if($customer_service->is_delete != 0){
            return $this->error('客服不存在');
        }

        if(ShopModel::where([
            ['customer_service_id','=',$customer_service_id]
        ])->find()){
            return $this->error('客服还有商铺,无法删除');
        }
        $customer_service->is_delete=1;
        $customer_service->save();

        return $this->success('删除成功');
    }

    public function appointKefu()
    {
        $shop_id=$this->request->param('shop_id/d',0);
        if(null === $shop = ShopModel::find($shop_id)){
            return $this->error('商铺不存在');
        }
    

        $customer_service_id=$this->request->param('customer_service_id/d',0);
        if(null === $customer_service = CustomerServiceModel::find($customer_service_id)){
            return $this->error('客服不存在');
        }
        if($customer_service->is_delete != 0){
            return $this->error('客服不存在');
        }

        if($shop->customer_service_id == $customer_service_id){
            return $this->error('这个客服本来就是这个商铺的客服');
        }

        $shop->customer_service_id=$customer_service_id;
        $shop->save();
        return $this->success('操作成功');
    }

    public function defaultKefu()
    {
        $customer_service_id=$this->request->param('customer_service_id/d',0);
        if($customer_service_id==0){
            return $this->success([]);
        }
        if(null === $customer_service = CustomerServiceModel::find($customer_service_id)){
            return $this->error('客服不存在');
        }
        if($customer_service->is_delete != 0){
            return $this->error('客服不存在');
        }
        Db::name('customer_service')->where('is_default',1)->update(['is_default'=>-1]);
        Db::name('customer_service')->where('customer_service_id',$customer_service_id)->update(['is_default'=>1]);
        return $this->success();
    }

    public function showShopPayment()
    {
        $shop_id=$this->request->param('shop_id/d',0);
        if(null === $shop = ShopModel::find($shop_id)){
            return $this->error('商铺不存在');
        }
        if($shop->expire_time<$this->request->time()){
            return $this->error('商铺已经过期了');
        }
        if(null === $payment =ShopPaymentModel::find($shop_id)){
            return $this->success([]);
        }
        $detail=[
            'type'=>$payment->type,
            'service_mach_id'=>$payment->service_mach_id,
            'mach_id'=>$payment->mach_id,
            'api_auth'=>$payment->api_auth,
            'api_cert'=>$payment->api_cert,
            'api_key'=>$payment->api_key,
        ];

        return $this->success(['detail'=>$detail]);
    }

    public function saveShopPayment()
    {
        $shop_id=$this->request->param('shop_id/d',0);
        if(null === $shop = ShopModel::find($shop_id)){
            return $this->error('商铺不存在');
        }
        if($shop->expire_time<$this->request->time()){
            return $this->error('商铺已经过期了');
        }

        $type     = $this->request->param('type/d');
        $service_mach_id  =  trim($this->request->param('service_mach_id'));
        $mach_id  =  trim($this->request->param('mach_id'));
        $api_auth = trim($this->request->param('api_auth'));
        $api_cert = trim($this->request->param('api_cert'));
        $api_key  = trim($this->request->param('api_key'));
        if($type != 0  && $type != 1){
            return $this->error('请选择支付类型');
        }
        if(empty($service_mach_id) && $type == 1){
            return $this->error('商户ID不能为空');
        }
        if(empty($mach_id) && $type == 0){
            return $this->error('商户ID不能为空');
        }
        if(empty($api_auth) && $type == 0){
            return $this->error('API秘钥不能为空');
        }
        if(empty($api_cert) && $type == 0){
            return $this->error('证书CERT内容不能为空');
        }
        if(empty($api_key)  && $type == 0){
            return $this->error('证书key内容不能为空');
        }
        if(null === $payment = ShopPaymentModel::find($shop_id)){
            $payment = new ShopPaymentModel();
            $payment->shop_id = $shop_id;
        }
        $payment->type = $type;
        if($type==0){
            $payment->mach_id = $mach_id;
            $payment->api_auth = $api_auth;
            $payment->api_cert = $api_cert;
            $payment->api_key = $api_key;
        }
        if($type==1){
            $payment->service_mach_id = $service_mach_id;
        }
        $payment->save();
        return $this->success('保存成功');
    }

    public function delShop()
    {
        $shop_id=$this->request->param('shop_id/d',0);
        if(null === $shop = ShopModel::find($shop_id)){
            return $this->error('商铺不存在');
        }

       Db::startTrans();
        try{
            $res1=$shop->delete();
            $res2=ShopAccountModel::where([
                ['shop_id','=',$shop_id]
            ])->delete();

            if($res1 && $res2){
                Db::commit();
                cache('miniapp_'.$shop_id,null); //删除小程序的缓存
                return $this->success('操作成功');
            }
            Db::rollback();
            return $this->error('操作失败');
        }catch(\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }
}
